package com.kingdee.openimport.patch_service.service.impl;

import com.kingdee.openimport.patch_service.enume.ErrorCode;
import com.kingdee.openimport.patch_service.enume.PatchType;
import com.kingdee.openimport.patch_service.exception.PatchException;
import com.kingdee.openimport.patch_service.service.ICheckService;
import com.kingdee.openimport.patch_service.service.IPatchVersionService;
import com.kingdee.openimport.patch_service.service.IRedisCacheService;
import com.kingdee.openimport.patch_service.util.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * Created by Niki on 2018/5/11 10:33
 */
@Service
public class CheckServiceImpl implements ICheckService {
    @Resource
    IRedisCacheService redisCacheService ;

    @Resource
    IPatchVersionService patchVersionService;

    @Override
    public boolean checkType(String type) throws PatchException {
        if (!StringUtils.isBlank(type)) {
            PatchType[] patchTypes = PatchType.values();
            for (PatchType patchType : patchTypes) {
                if (type.toUpperCase().equals(patchType.name().toUpperCase())) {
                    return true;
                }
            }
        }
        throw ErrorCode.returnException(ErrorCode.TYPE_ERROR);
    }

    @Override
    public boolean checkFile(MultipartFile file) throws PatchException {
        if (file == null || file.isEmpty() || file.getSize() <= 0) {
            throw ErrorCode.returnException(ErrorCode.FILE_ERROR);
        }

        if (!file.getOriginalFilename().endsWith(".class") && !file.getOriginalFilename().endsWith(".jsp")) {
            throw ErrorCode.returnException(ErrorCode.FILE_TYPE_ERROR);
        }
        return true;
    }

    @Override
    public boolean checkVersion(String version) throws PatchException {
        if (!StringUtils.isBlank(version)) {
            if (version.equals(redisCacheService.getLatestVersion())) {
                return true;
            }

            if (!redisCacheService.versionInExist(version)) {
                if (patchVersionService.exist(version)) {
                    return true;
                }
            }
        }
        throw ErrorCode.returnException(ErrorCode.VERSION_NOT_EXIST);
    }

}
